<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>前端路由机制实现</title>
</head>

<body>
    <nav class="nav-box">
        <a href="/">首页</a>
        <a href="/product">产品中心</a>
        <a href="/personal">个人中心</a>
    </nav>
    <div class="view-box"></div>

    <!-- IMPORT JS -->
    <script>
        const viewBox = document.querySelector('.view-box'),
            navBox = document.querySelector('.nav-box')

        // 构建路由表
        const routes = [{
            path: '/',
            component: '首页的内容'
        }, {
            path: '/product',
            component: '产品中心的内容'
        }, {
            path: '/personal',
            component: '个人中心的内容'
        }, {
            path: '*',
            component: '404错误页面'
        }]

        // 路由匹配的方法
        const matchRoute = function matchRoute() {
            let pathname = location.pathname
            let item = routes.find(item => item.path === pathname)
            if (!item) item = routes.find(item => item.path === '*')
            if (!item) {
                viewBox.innerHTML = ''
                return
            }
            viewBox.innerHTML = item.component
        }

        // 基于HistoryAPI实现路由(地址)跳转
        navBox.addEventListener('click', function (ev) {
            let target = ev.target,
                targetTag = target.tagName
            if (targetTag === 'A') {
                ev.preventDefault() //阻止A标签的默认行为
                history.pushState({}, "", target.href)
                matchRoute()
            }
        })
        history.pushState({}, "", "/")
        matchRoute()

        // 基于 popstate 事件，监听前进后退
        window.addEventListener('popstate', matchRoute)
    </script>
</body>

</html>